package com.xiaolanshu.controller;

import com.xiaolanshu.entity.Goods;
import com.xiaolanshu.entity.Order;
import com.xiaolanshu.entity.ShoppingCart;
import com.xiaolanshu.entity.User;
import com.xiaolanshu.exception.BusinessException;
import com.xiaolanshu.interceptor.UserHolder;
import com.xiaolanshu.service.GoodsService;
import com.xiaolanshu.service.OrderService;
import com.xiaolanshu.service.ShoppingCartService;
import com.xiaolanshu.service.UserService;
import com.xiaolanshu.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;

    /**
     * 查询所有购物车商品
     * @return
     */
    @GetMapping
    public ResponseEntity shoppingCartInfo(){
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();

        //查询所有购物车商品
        List<ShoppingCart> shoppingCartsList = shoppingCartService.shoppingCartInfo(userId);
        return  ResponseEntity.ok(shoppingCartsList);
    }

    /**
     * 删除购物程商品
     * @param goodsId
     * @return
     */
    @PutMapping("/remove/{goodsId}")
    public ResponseEntity removeGoods(@PathVariable Long goodsId){
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();
        int i = shoppingCartService.removeGoods(userId, goodsId);
        if(!String.valueOf(i).equals("")){
            return ResponseEntity.status(200).body("删除成功");
        }
        else {
            //更新失败抛出自定义业务异常
            throw new BusinessException(ErrorResult.crudError());
        }
    }

    /**
     * 添加商品到购物车
     * @param goodsId
     * @param count
     * @return
     */
    @PostMapping("/add/{goodsId}")
    public ResponseEntity addGoods(@PathVariable Long goodsId,
                                   @RequestParam(defaultValue = "1") Integer count){
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();
        //通过goodsId获取要添加的商品信息
        Goods goods = goodsService.findGoods(goodsId);
        //根据商品id查询购物车中是否已经存在该商品
        ShoppingCart goodsCart = shoppingCartService.findGoods(userId, goodsId);
        if(goodsCart != null){
            return ResponseEntity.status(500).body("购物车已存在该商品");
        }

        //将商品信息添加到购物车
        shoppingCartService.saveGoods(userId,goods,count);

        return ResponseEntity.status(200).body("添加成功");
    }

    /**
     * 增加购物车商品数量
     * @param goodsId
     * @return
     */
    @PostMapping("/addCount/{goodsId}")
    public ResponseEntity addGoodsCount(@PathVariable Long goodsId){
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();

        //根据用户id和商品id增加商品数量
        int i = shoppingCartService.addGoodsCount(userId, goodsId);

        if(!String.valueOf(i).equals("")){
            return ResponseEntity.status(200).body("商品数量加1");
        }
        else {
            //更新失败抛出自定义业务异常
            throw new BusinessException(ErrorResult.crudError());
        }

    }

    /**
     * 减少购物车商品数量
     * @param goodsId
     * @return
     */
    @PostMapping("/reduceCount/{goodsId}")
    public ResponseEntity reduceGoodsCount(@PathVariable Long goodsId){
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();

        //根据用户id和商品id减少商品数量
        shoppingCartService.reduceGoodsCount(userId,goodsId);

        return ResponseEntity.status(200).body("商品数量减1");
    }

    /**
     * 购物车结算
     * @param goodsIdList
     * @return
     */
    @PostMapping("/settlement")
    public ResponseEntity settlement(@RequestParam Long[] goodsIdList){

        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();

        //总的返利金额
        Double returnAmounts = 0D;
        //所有商品总金额
        Double amounts = 0D;
        //根据商品id列表遍历获取商品的返利率和成本
        for (Long l:goodsIdList
             ) {
            Goods goods = goodsService.findGoods(l);
            Double returnRate = goods.getReturnRate();
            Double cost = goods.getCost();

            //根据用户id和商品id查询购物车中的商品信息
            ShoppingCart shoppingCart = shoppingCartService.findGoods(userId,l);
            //计算每种商品的返利金额并保留2位小数
            DecimalFormat df=new DecimalFormat("0.00");
            Double returnAmount = Double.valueOf(df.format(shoppingCart.getAmount()*returnRate));
            //计算每种商品的成本并保留2为小数
            Double costs = Double.valueOf(df.format(cost*shoppingCart.getCount()));

            //将购物车商品信息和返利金额和总成本添加到订单
            orderService.addShoppingCartGoods(shoppingCart,returnAmount,costs);

            //将所有商品总金额相加
            amounts += shoppingCart.getAmount();
            //将所有返利金额相加
            returnAmounts += returnAmount;

        }
        //判断用户余额是否足够支付
        User user = userService.findUser(userId);
        if(amounts > user.getMoney()){
            //支付失败，抛出自定义业务异常
            throw new BusinessException(ErrorResult.payError());
        }

        //根据商品总金额扣除用户的余额
        userService.reduceMoney(amounts,userId);
        //将所有返利金额保存到购买的用户的信息里
        userService.saveReturnAmount(returnAmounts,userId);

        //结算完从购物车删除这些商品
        for (Long goodsId:goodsIdList
             ) {
            shoppingCartService.delete(goodsId,userId);
        }

        return ResponseEntity.status(200).body("结算成功");
    }
}
